package com.utils;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;


public class RequestUtil {

    public static final Logger logger = LoggerFactory.getLogger(RequestUtil.class);

    /**
     * 发送http请求
     *
     * @param url
     * @param requestMethod 请求方式get post put delete，自定义枚举
     * @param header
     * @param param
     * @return
     */
    public JSONObject sendHttp(String url, HttpRequestMethodEnum requestMethod, JSONObject header, JSONObject param) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse httpresponse = null;
        JSONObject response = null;
        HttpRequestBase httpRequest = requestMethod.createRequest(url);

        //加载Header
        for (Map.Entry<String, Object> entry : header.entrySet()) {
            httpRequest.addHeader(entry.getKey(), (String) entry.getValue());
        }

        try {
            if (requestMethod.equals(HttpRequestMethodEnum.get)) {
                httpresponse = httpclient.execute(httpRequest);
            } else if (requestMethod.equals(HttpRequestMethodEnum.post)) {
                httpRequest.addHeader("Content-Type", "application/json;charset=UTF-8");
                StringEntity se = new StringEntity(param.toString(), "utf-8");
                ((HttpEntityEnclosingRequest) httpRequest).setEntity(se);
                httpresponse = httpclient.execute(httpRequest);
            } else if (requestMethod.equals(HttpRequestMethodEnum.post_form)) {
                // 构建FORM请求体
                List<NameValuePair> nvp = new ArrayList<>();
                for (Map.Entry<String, Object> entry : param.entrySet()) {
                    nvp.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue()));
                }
                httpRequest.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                ((HttpEntityEnclosingRequest) httpRequest).setEntity(new UrlEncodedFormEntity(nvp, Consts.UTF_8));
                httpresponse = httpclient.execute(httpRequest);
            }

            assert httpresponse != null;
            int statusCode = httpresponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(httpresponse.getEntity());
                logger.info("Interface execution result: {}", result);
                response = JSON.parseObject(result);
            } else {
                logger.error("Interface execution exception HttpStatus: {}", statusCode);
                ReportUtil.log("HttpStatus:" + statusCode);
            }
        } catch (IOException e) {
            logger.error("Interface exception!!!");
            e.printStackTrace();
        } finally {
            try {
                //7、关闭响应对象;
                if (httpresponse != null) {
                    httpresponse.close();
                }
                //8、关闭HttpClient.
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }
}
